package com.actionsky.action;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.actionsky.dao.SearchDAO;
import com.actionsky.entity.*;

public class Search extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private List<Article> list = null;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String keyword = request.getParameter("searchString")==null?request.getSession().getAttribute("keyword").toString():request.getParameter("searchString").trim();
		/*
		if(request.getSession().getAttribute("keyword")==null)
			keyword = request.getParameter("searchString").trim();
		else
			keyword = request.getSession().getAttribute("keyword").toString();
		*/
		request.getSession().setAttribute("keyword", keyword);
		//页数
		int page_number = Integer.parseInt(request.getParameter("page"));
		int int_page_number=(page_number-1)*10;		//int_page_number 从第几条记录开始
		int rowcount=0;
		//判断关键字是否为空字符串
		if(keyword.length()==0){
			request.getSession().removeAttribute("keyword");
			list = null;	
		}else{
		
			//判断关键字中是否含有空格或逗号
			if(keyword.indexOf(" ")>0 || keyword.indexOf(",")>0){
				//设定规则式样
				Pattern pattern = Pattern.compile("[, ]+");
				String[] keywords = pattern.split(keyword); 
				list = SearchDAO.findArticlesByTitle(keywords,int_page_number);
				rowcount = SearchDAO.countByTitle(keywords);
			}else{
				list = SearchDAO.findArticlesByTitle(keyword,int_page_number);
				rowcount = SearchDAO.countByTitle(keyword);
			}
			if(rowcount==0) rowcount=1;
			
			PageSet pageset=new PageSet();
			pageset.setRowcount(rowcount);
			pageset.setCurrentpage(page_number);
			pageset.setPagecount((rowcount+10-1)/10);
			pageset.setPagesize(10);
			request.getSession().setAttribute("pageset", pageset);
		}
		
		request.getSession().setAttribute("search_result", list);
		response.sendRedirect("search/result.jsp");
		//request.getRequestDispatcher("/search/result.jsp").forward(request, response);

	}

	public void init() throws ServletException {
	}
	public void destroy() {
		super.destroy(); 
	}

}
